﻿using System;
using System.Globalization;
using DomainModel;
using Services.Abstract;

namespace Services.Concrete
{
    public class DateTimeService : IDateTimeService
    {
        public int GetWeekNoByCurrentDay(StudySemester semester, DateTime currentDate)
        {
            if (semester.EndDate.Date < currentDate.Date)
                return 1;

            Calendar calendar = new GregorianCalendar();
            int semesterBeginWeekNo = calendar.GetWeekOfYear(semester.BeginDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            int currentDateWeekNo = calendar.GetWeekOfYear(currentDate, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

            int weekDiff = currentDateWeekNo - semesterBeginWeekNo;

            if (weekDiff % 2 == 0)
            {
                return 1;
            }

            return 2;
        }

        public int GetDayNoByCurrentDay(DateTime currentDate)
        {
            DayOfWeek day = currentDate.DayOfWeek;

            switch (day)
            {
                case DayOfWeek.Monday:
                    return 1;
                case DayOfWeek.Tuesday:
                    return 2;
                case DayOfWeek.Wednesday:
                    return 3;
                case DayOfWeek.Thursday:
                    return 4;
                case DayOfWeek.Friday:
                    return 5;
                case DayOfWeek.Saturday:
                    return 6;
                case DayOfWeek.Sunday:
                    return 7;
            }
            return 0;
        }

        public void GetWeekBeginAndEndDate(StudySemester semester, int weekNo, out DateTime weekBeginDate, out DateTime weekEndDate)
        {
            var weekBegin = semester.BeginDate.AddDays(7 * (weekNo-1));
            var weekEnd = weekBegin;

            while (weekBegin.DayOfWeek != DayOfWeek.Monday && weekBegin.ToShortDateString() != semester.BeginDate.ToShortDateString())
                weekBegin = weekBegin.AddDays(-1);

            while (weekEnd.DayOfWeek != DayOfWeek.Sunday && weekEnd.ToShortDateString() != semester.EndDate.ToShortDateString())
                weekEnd = weekEnd.AddDays(1);

            weekBeginDate = weekBegin;
            weekEndDate = weekEnd;
        }
    }
}